<template>
  <div class="common-layout">
    <el-container>
      <el-header style="color:#fff;background-color:#545c64;margin-bottom: 2px;">
        <p >当前登录人:{{ useStore.userName }}</p>
        <el-button style="float:right" type="primary" @click="Logout">退出登录</el-button>
      </el-header>
      <el-container>
        <el-aside width="200px">
          <el-menu
        active-text-color="#ffd04b"
        background-color="#545c64"
        class="el-menu-vertical-demo"
        default-active="GetProductInfo"
        text-color="#fff"
        @open="handleOpen"
        @close="handleClose"
        router
        style="height:1900px"
      >
      <el-sub-menu index="1">
      <template #title>
        <el-icon><User /></el-icon>
        <span>菜单管理</span>
      </template>
      <div v-for="(item, index) in PermissionData" :key="index" >
        <DynamicMenu :item="item" />
      </div>
    </el-sub-menu>
      </el-menu>
        </el-aside>
        <el-main>
          <RouterView></RouterView>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref,onMounted } from 'vue'
import { ElMessage } from 'element-plus';
import { useCounterStore } from '@/stores/counter';
const useStore=useCounterStore();
import { useRouter } from 'vue-router';
const router = useRouter();
import DynamicMenu from '@/components/DynamicMenu.vue'; // 导入递归菜单组件
import { api1, api2 } from '@/main';
//@ts-ignore
import Cookies from 'js-cookie'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import type { RouteRecordRaw } from 'vue-router';


const handleOpen = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)//Test  ['1', 'Test']
}
const handleClose = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}

interface Permission{
  permissionId: number,
  permissionName: string,
  path: string,
  name: string,
  component: string,
  children?: Permission[]
}
const PermissionData=ref<Permission[]>([]);

const Logout=()=>{
  router.push('/');
}
onMounted(()=>{
  loadPermission();
})

const loadPermission= ()=>{
  api1.get('/api/User/GetTreePermissionList')
  .then(async res=>{
    PermissionData.value=res.data.data;
    console.log(PermissionData.value);
    await addDynamicRoutes(PermissionData.value);
  })
}

// 动态添加路由的函数
const addDynamicRoutes = async (permissionData: Permission[]) => {
  await Promise.all(permissionData.map(async (permission) => {
    console.log(permission);

    // 动态导入组件
    const componentPath = `../views/${permission.component}.vue`;
    const component = await import(`${componentPath}`);

    // 创建路由对象
    const route: RouteRecordRaw = {
      path: permission.path,
      name: permission.name,
      component: component.default, // 访问默认导出
      children: permission.children
        ? await Promise.all(permission.children.map(async (child) => {
            const childComponentPath = `../views/${child.component}.vue`;
            const childComponent = await import(`${childComponentPath}`);
            return {
              path: child.path,
              name: child.name,
              component: childComponent.default,
            };
          }))
        : [], // 如果有子路由，递归生成子路由
    };

    console.log(`路由配置: ${JSON.stringify(route)}`); // 获取当前的路由配置
    const routes = router.options.routes;

    // 找到父路由 MenuView
    const menuViewRoute = routes.find(route => route.name === 'MenuView');

    // 确保 menuViewRoute 存在
    if (menuViewRoute) {
      menuViewRoute.children?.push(route); // 使用可选链操作符，确保 children 存在
      console.log(route);

      // 重新添加路由配置
      router.addRoute(menuViewRoute);
    } else {
      console.error('父路由 MenuView 未找到，无法添加子路由');
    }
  }));

  // 重新加载当前路由，确保新路由生效
  router.replace(router.currentRoute.value.path);
  const routes = router.getRoutes();
  console.log(routes);
};

</script>
